package com.mzpai.web.controller;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.mzpai.product.constant.UserSuccessKilledStatusConstants;
import com.mzpai.product.exception.ProductResException;
import com.mzpai.product.exception.ProductResExceptionCode;
import com.mzpai.product.model.StoreSeckill;
import com.mzpai.product.model.UserSuccessKilled;
import com.mzpai.product.service.StoreSeckillService;
import com.mzpai.product.service.UserSuccessKilledService;
import com.mzpai.product.vo.SeckillOrderVerifyResultVo;
import com.mzpai.product.vo.UserSeckillOrderReqVo;
import com.mzpai.product.vo.UserSeckillSuccessOrderVo;
import com.mzpai.util.StringUtils;
import com.mzpai.vo.ResponseVo;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
@Api(value = "用户描述相关通用接口")
@RestController
@RequestMapping("/userSeckill")
public class UserSeckillController extends BaseController {

	
	private static Logger log = LoggerFactory.getLogger(UserSeckillController.class);
	
	@Autowired 
	private UserSuccessKilledService userSuccessKilledService;
	
	@Autowired 
	private StoreSeckillService storeSeckillService;
	
	
	
	@ApiOperation(value = "秒杀订单校验接口")
    @RequestMapping(value = "/seckillOrderVerify")
    public ResponseVo<SeckillOrderVerifyResultVo> seckillOrderVerify(@RequestBody List<UserSeckillSuccessOrderVo> listUserSeckillSuccess){
		log.info("msg1=开始秒杀下单前校验接口,,method=seckillOrderVerify,,listUserSeckillSuccess={}",JSON.toJSONString(listUserSeckillSuccess));
		
		
		ResponseVo<SeckillOrderVerifyResultVo> resVo=new ResponseVo<SeckillOrderVerifyResultVo>();
		SeckillOrderVerifyResultVo seckillOrderVerifyResultVo=new SeckillOrderVerifyResultVo();
        List<UserSeckillSuccessOrderVo> seckillList=listUserSeckillSuccess;
        
        
		if(seckillList==null){
			resVo.setCode(ProductResExceptionCode.SECKILL_PRODUCT_NULL.getCode());
			resVo.setMessage(ProductResExceptionCode.SECKILL_PRODUCT_NULL.getMessage());
			resVo.setResult(seckillOrderVerifyResultVo);
			return resVo;
		}
		
		List<String> paramVerifyList=new ArrayList<String>();
		List<String> businessVerifyList=new ArrayList<String>();
		
		for(UserSeckillSuccessOrderVo orderVo:seckillList){
			verifyReqParam(orderVo,paramVerifyList);
			verifyBusiness(orderVo,businessVerifyList);
		}
		
		if((paramVerifyList!=null&&!paramVerifyList.isEmpty()) || (businessVerifyList!=null&&!businessVerifyList.isEmpty())){
			resVo.setCode(ProductResExceptionCode.SECKILL_VERIFY_FAIL.getCode());
			resVo.setMessage(ProductResExceptionCode.SECKILL_VERIFY_FAIL.getMessage());
			seckillOrderVerifyResultVo.setParamVerifyList(paramVerifyList);
			seckillOrderVerifyResultVo.setBusinessVerifyList(businessVerifyList);
		}
		resVo.setResult(seckillOrderVerifyResultVo);
    	return resVo;
	}
	
	private List<String> verifyBusiness(UserSeckillSuccessOrderVo orderVo,List<String> businessVerifyList){
		
		Integer storeId=orderVo.getStoreId();
		String userId=orderVo.getUserId();
		String userPhoe=orderVo.getUserPhone();
		Integer productId=orderVo.getProductId();
		Integer productAttrvalueId=orderVo.getProductAttrvalueId();
		Integer seckillId=orderVo.getSeckillId();
		Integer buyNum=orderVo.getBuyNum();
		
		//用户购买限制  统计当前用户当前商品购买数量
		
		Map<String,Object> countMap=new HashMap<String,Object>();
		List<Integer> stateList=new ArrayList<Integer>();
		stateList.add(1);
		stateList.add(2);
		countMap.put("userId", userId);
		countMap.put("seckillId", seckillId);
		countMap.put("stateList", stateList);
		countMap.put("productAttrvalueId", productAttrvalueId);
		
		StoreSeckill storeSeckill=storeSeckillService.queryByPrimaryId(seckillId);
		String productName=storeSeckill.getProductName();
		
		Integer buyCount=userSuccessKilledService.countTotalByUserIdAndSeckillId(countMap);
		
		Integer limitNum=storeSeckill.getNum();
		
		if(buyCount>limitNum){
			businessVerifyList.add("商品["+productName+"],"+ProductResExceptionCode.SECKILL_BUY_OVER.getMessage());
		}
		
		//查询结果
		Integer stock=storeSeckill.getStock();
		Date stopTime=storeSeckill.getStopTime();
		if(buyNum>stock){
			businessVerifyList.add("商品["+productName+"],"+ProductResExceptionCode.SECKILL_PRODUCT_NOT_SUFFICIENT.getMessage());
		}
		int compareToBefore=stopTime.compareTo(new Date());
		if(compareToBefore<0){
			businessVerifyList.add("商品["+productName+"],"+ProductResExceptionCode.SECKILL_PRODUCT_TIME_END.getMessage());
		}
		
		return businessVerifyList;
		
	}
	
	private List<String> verifyReqParam(UserSeckillSuccessOrderVo orderVo,List<String> paramVerifyList){
		Integer storeId=orderVo.getStoreId();
		String userId=orderVo.getUserId();
		String userPhoe=orderVo.getUserPhone();
		Integer productId=orderVo.getProductId();
		Integer productAttrvalueId=orderVo.getProductAttrvalueId();
		Integer seckillId=orderVo.getSeckillId();
		if(productId==null){
			paramVerifyList.add("秒杀ID["+seckillId+"],"+ProductResExceptionCode.PRODUCTCODE_LIST_NULL.getMessage());
		}
		
		if(productAttrvalueId==null){
			paramVerifyList.add("秒杀ID["+seckillId+"],"+ProductResExceptionCode.PRODUCT_ATTRVALUE_ID_NULL.getMessage());
		}
		
		if(seckillId==null){
			paramVerifyList.add("秒杀ID["+seckillId+"],"+ProductResExceptionCode.SECKILL_ID_NULL.getMessage());
		}
		
		if(storeId==null){
			paramVerifyList.add("秒杀ID["+seckillId+"],"+ProductResExceptionCode.STOREID_NULL.getMessage());
		}
		
		if(StringUtils.isNullOrBlank(userId)){
			paramVerifyList.add("秒杀ID["+seckillId+"],"+ProductResExceptionCode.USER_IDNULL_ERROR.getMessage());
		}
		return paramVerifyList;
	}
	
	
	@ApiOperation(value = "秒杀下单成功")
    @RequestMapping(value = "/orderSuccess")
    public ResponseVo<Boolean> orderSuccess(@RequestBody List<UserSeckillSuccessOrderVo> listUserSeckillSuccess){
		
		log.info("msg1=开始秒杀下单成功占用库存,,method=orderSuccess,,listUserSeckillSuccess={}", JSON.toJSONString(listUserSeckillSuccess));
		
		List<UserSeckillSuccessOrderVo> seckillList=listUserSeckillSuccess;
		
		ResponseVo<Boolean> resVo=new ResponseVo<Boolean>();
		if(seckillList==null){
			ResponseVo<Boolean> resultVo=new ResponseVo<Boolean>();
			resultVo.setCode(ProductResExceptionCode.SECKILL_PRODUCT_NULL.getCode());
			resultVo.setMessage(ProductResExceptionCode.SECKILL_PRODUCT_NULL.getMessage());
			resultVo.setResult(false);
			return resultVo;
		}
		
		List<UserSuccessKilled> userSuccessKilledList=buildUserSuccessKilledList(seckillList);
		
		try{
			userSuccessKilledService.saveSeckillSuccessOrder(userSuccessKilledList);
			resVo.setResult(true);
		} catch(ProductResException pe){
			logger.error("msg1= 扣减库存信息异常， {}", pe);
			resVo.setCode(pe.getCode());
			resVo.setMessage(pe.getMessage());
			resVo.setResult(false);
		}catch(Exception e) {
			logger.error("msg1= 扣减库存信息异常， {}", e);
			resVo.setCode(-1);
			resVo.setMessage("操作失败!");
			resVo.setResult(false);
		}
    	return resVo;
	}
	
	
	
	
	private List<UserSuccessKilled> buildUserSuccessKilledList(List<UserSeckillSuccessOrderVo> seckillList){
		
		List<UserSuccessKilled> list=new ArrayList<UserSuccessKilled>();
		for(UserSeckillSuccessOrderVo vo:seckillList){
			
			Integer seckillId=vo.getSeckillId();
			Integer productId=vo.getProductId();
			Integer productAttrvalueId=vo.getProductAttrvalueId();
			Integer storeId=vo.getStoreId();
			String userId=vo.getUserId();
			String userPhone=vo.getUserPhone();
			String orderId=vo.getOrderId();
			Integer buyNum=vo.getBuyNum();
			//设置值
			UserSuccessKilled userSuccessKilled=new UserSuccessKilled();
			userSuccessKilled.setSeckillId(seckillId);
			userSuccessKilled.setProductId(productId);
			userSuccessKilled.setProductAttrvalueId(productAttrvalueId);
			userSuccessKilled.setStoreId(storeId);
			userSuccessKilled.setUserPhone(userPhone);
			userSuccessKilled.setUserId(userId);
			userSuccessKilled.setOrderId(orderId);
			userSuccessKilled.setBuyNum(buyNum);
			userSuccessKilled.setState(UserSuccessKilledStatusConstants.SUCCESS_SKILL_STATUS_2);
			userSuccessKilled.setCreateTime(new Date());
			//放入集合
			list.add(userSuccessKilled);
		}
		return list;
	}
	
	
	@ApiOperation(value = "秒杀订单支付成功调用接口")
    @RequestMapping(value = "/orderPaySuccess")
    public ResponseVo<Boolean> orderPaySuccess(@RequestBody UserSeckillOrderReqVo seckillPaySuccessOrderReqVo){
		
		log.info("msg1=开始秒杀订单支付成功调用接口,,method=orderPaySuccess,,seckillPaySuccessOrderReqVo={}", JSON.toJSONString(seckillPaySuccessOrderReqVo));
		
		String orderId=seckillPaySuccessOrderReqVo.getOrderId();
		Integer storeId=seckillPaySuccessOrderReqVo.getStoreId();
		String userId=seckillPaySuccessOrderReqVo.getUserId();
		String userPhoe=seckillPaySuccessOrderReqVo.getUserPhone();
		
		ResponseVo<Boolean> resVo=new ResponseVo<Boolean>();
		
		if(StringUtils.isNullOrBlank(orderId)){
			ResponseVo<Boolean> resultVo=new ResponseVo<Boolean>();
			resultVo.setCode(ProductResExceptionCode.ORDER_ID_NULL.getCode());
			resultVo.setMessage(ProductResExceptionCode.ORDER_ID_NULL.getMessage());
			resultVo.setResult(false);
			return resultVo;
		}
		
		
		if(storeId==null){
			ResponseVo<Boolean> resultVo=new ResponseVo<Boolean>();
			resultVo.setCode(ProductResExceptionCode.STOREID_NULL.getCode());
			resultVo.setMessage(ProductResExceptionCode.STOREID_NULL.getMessage());
			resultVo.setResult(false);
			return resultVo;
		}
		
		if(StringUtils.isNullOrBlank(userId)){
			ResponseVo<Boolean> resultVo=new ResponseVo<Boolean>();
			resultVo.setCode(ProductResExceptionCode.USER_IDNULL_ERROR.getCode());
			resultVo.setMessage(ProductResExceptionCode.USER_IDNULL_ERROR.getMessage());
			resultVo.setResult(false);
			return resultVo;
		}
		
		Map<String,Object> queryMap=new HashMap<String,Object>();
		queryMap.put("orderId", orderId);
		queryMap.put("state", 2);
		List<UserSuccessKilled> listUserSuccessKilled=userSuccessKilledService.getList(queryMap);
		
		if(listUserSuccessKilled==null || listUserSuccessKilled.isEmpty()){
			ResponseVo<Boolean> resultVo=new ResponseVo<Boolean>();
			resultVo.setCode(ProductResExceptionCode.ORDER_SECKILL_NULL.getCode());
			resultVo.setMessage(ProductResExceptionCode.ORDER_SECKILL_NULL.getMessage());
			resultVo.setResult(false);
			return resultVo;
		}
		
		List<StoreSeckill> listStoreSeckill=new ArrayList<StoreSeckill>();
		
		for(UserSuccessKilled usk:listUserSuccessKilled){
			Integer seckillId=usk.getSeckillId();
			Integer buyNum=usk.getBuyNum();
			
			StoreSeckill queryStoreSeckill=storeSeckillService.queryByPrimaryId(seckillId);
			Integer currentSales=queryStoreSeckill.getSales();
			
			StoreSeckill updateStoreSeckill=new StoreSeckill();
			updateStoreSeckill.setId(seckillId);
			updateStoreSeckill.setSales(currentSales+buyNum);
			listStoreSeckill.add(updateStoreSeckill);
		}
		
		UserSuccessKilled updateUserSuccessKilled=new UserSuccessKilled();
		updateUserSuccessKilled.setOrderId(orderId);
		updateUserSuccessKilled.setState(UserSuccessKilledStatusConstants.SUCCESS_SKILL_STATUS_1);
		try{
			userSuccessKilledService.updateUserSuccessKilledAndStoreSeckill(updateUserSuccessKilled,listStoreSeckill);
			resVo.setResult(true);
		} catch(ProductResException pe){
			logger.error("msg1= 更新支付信息异常， {}", pe);
			resVo.setCode(pe.getCode());
			resVo.setMessage(pe.getMessage());
			resVo.setResult(false);
		}catch(Exception e) {
			logger.error("msg1= 更新支付信息异常， {}", e);
			resVo.setCode(-1);
			resVo.setMessage("操作失败!");
			resVo.setResult(false);
		}
    	return resVo;
	}
	
	
	
	@ApiOperation(value = "秒杀订单取消调用接口")
    @RequestMapping(value = "/seckillOrderCancel")
    public ResponseVo<Boolean> seckillOrderCancel(@RequestBody UserSeckillOrderReqVo userSeckillOrderReqVo){
		
		log.info("msg1=开始秒杀订单取消调用接口,,method=seckillOrderCancel,,userSeckillOrderReqVo={}", JSON.toJSONString(userSeckillOrderReqVo));
		
		String orderId=userSeckillOrderReqVo.getOrderId();
		Integer storeId=userSeckillOrderReqVo.getStoreId();
		String userId=userSeckillOrderReqVo.getUserId();
		String userPhoe=userSeckillOrderReqVo.getUserPhone();
		
		ResponseVo<Boolean> resVo=new ResponseVo<Boolean>();
		
		if(StringUtils.isNullOrBlank(orderId)){
			ResponseVo<Boolean> resultVo=new ResponseVo<Boolean>();
			resultVo.setCode(ProductResExceptionCode.ORDER_ID_NULL.getCode());
			resultVo.setMessage(ProductResExceptionCode.ORDER_ID_NULL.getMessage());
			resultVo.setResult(false);
			return resultVo;
		}
		
		
		if(storeId==null){
			ResponseVo<Boolean> resultVo=new ResponseVo<Boolean>();
			resultVo.setCode(ProductResExceptionCode.STOREID_NULL.getCode());
			resultVo.setMessage(ProductResExceptionCode.STOREID_NULL.getMessage());
			resultVo.setResult(false);
			return resultVo;
		}
		
		if(StringUtils.isNullOrBlank(userId)){
			ResponseVo<Boolean> resultVo=new ResponseVo<Boolean>();
			resultVo.setCode(ProductResExceptionCode.USER_IDNULL_ERROR.getCode());
			resultVo.setMessage(ProductResExceptionCode.USER_IDNULL_ERROR.getMessage());
			resultVo.setResult(false);
			return resultVo;
		}
		
		Map<String,Object> queryMap=new HashMap<String,Object>();
		queryMap.put("orderId", orderId);
		queryMap.put("state", 2);
		List<UserSuccessKilled> listUserSuccessKilled=userSuccessKilledService.getList(queryMap);
		
		if(listUserSuccessKilled==null || listUserSuccessKilled.isEmpty()){
			ResponseVo<Boolean> resultVo=new ResponseVo<Boolean>();
			resultVo.setCode(ProductResExceptionCode.ORDER_SECKILL_NULL.getCode());
			resultVo.setMessage(ProductResExceptionCode.ORDER_SECKILL_NULL.getMessage());
			resultVo.setResult(false);
			return resultVo;
		}
		
		List<StoreSeckill> listStoreSeckill=new ArrayList<StoreSeckill>();
		
		for(UserSuccessKilled usk:listUserSuccessKilled){
			Integer seckillId=usk.getSeckillId();
			Integer buyNum=usk.getBuyNum();
			
			StoreSeckill queryStoreSeckill=storeSeckillService.queryByPrimaryId(seckillId);
			Integer currentStock=queryStoreSeckill.getStock();
			StoreSeckill updateStoreSeckill=new StoreSeckill();
			updateStoreSeckill.setId(seckillId);
			updateStoreSeckill.setStock(currentStock-buyNum);
			listStoreSeckill.add(updateStoreSeckill);
		}
		
		UserSuccessKilled updateUserSuccessKilled=new UserSuccessKilled();
		updateUserSuccessKilled.setOrderId(orderId);
		updateUserSuccessKilled.setState(UserSuccessKilledStatusConstants.SUCCESS_SKILL_STATUS_INVALID);
		try{
			userSuccessKilledService.updateUserSuccessKilledAndStoreSeckill(updateUserSuccessKilled,listStoreSeckill);
			resVo.setResult(true);
		} catch(ProductResException pe){
			logger.error("msg1= 取消更新库存信息异常， {}", pe);
			resVo.setCode(pe.getCode());
			resVo.setMessage(pe.getMessage());
			resVo.setResult(false);
		}catch(Exception e) {
			logger.error("msg1= 取消更新库存信息异常， {}", e);
			resVo.setCode(-1);
			resVo.setMessage("操作失败!");
			resVo.setResult(false);
		}
    	return resVo;
	}
	
}